package com.fxu.docx2md.dto;

import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 文档段落
 * @author fangxu
 * @version 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MdPara {
    /** 级别 */
    private Integer level;
    /** 是否居中 */
    private boolean center;
    /** 是否加粗 */
    private boolean image;
    /** 是否加粗 */
    private boolean info;
    /** 字体大小 */
    private Integer size;
    /** 字体大小 */
    private Integer style;
    /** 标题级别 */
    private Integer heading;
    /** 内容 */
    private List<MdText> texts;

    public String getText() {
        if (level != null) {
            texts.forEach(v -> v.setBold(false));
        }
        String _text = getLevelTxt() + texts.stream().map(MdText::getText).collect(Collectors.joining());
        if (_text.startsWith("**") && _text.endsWith("**")) {
            _text = "**" + _text.replace("**", "") + "**";
        }
        _text = _text.replace("****", "");
        String temp = StrUtil.trim(_text);
        if (temp.endsWith("=") || temp.endsWith("＝") || temp.endsWith("＝**") || temp.endsWith("=**") || temp.endsWith("分录：") || temp.endsWith("分录：**")) {
            _text = _text + "\n___";
            if (temp.endsWith("分录：") || temp.endsWith("分录：**")) {
                _text = _text + "\n___";
                _text = _text + "\n___";
            }
        }
        if (center && !image && level == null && StrUtil.isNotEmpty(_text)) {
            _text = "<center>" + _text + "</center>";
        }
        if (!center && !image && level == null && StrUtil.isNotEmpty(_text) && (temp.startsWith("【案例") || temp.startsWith("【例"))) {
            String prv = _text.substring(0, _text.indexOf("】") + 1);
            String nxt = _text.substring(_text.indexOf("】") + 1);
            _text = "::: info " + prv + "\n" + nxt + "\n:::\n";
        }

        if (StrUtil.isNotEmpty(_text) && !_text.startsWith("{") && _text.contains("<b><b>") && _text.contains("</b></b>")) {
            _text = "<span class=\"p-y\">" + _text + "</span>";
        }
        return _text + "\n";
    }

    private String getLevelTxt() {
        //  || CollUtil.isEmpty(texts)
        if (level == null || image) return "";
        // if (CollUtil.findOne(texts, v -> StrUtil.isNotEmpty(v.getText())) == null) return "";
        if (level == 1) return "# ";
        if (level == 2) return "## ";
        if (level == 3) return "### ";
        if (level == 4) return "#### ";
        if (level == 5) return "##### ";
        return "";
    }
}
